#encoding=utf-8
'''
Created on 2015-3-29

@author: cooler
'''
import sys,os
reload(sys)
sys.setdefaultencoding('utf8')

import  logging,  os.path
import math, time
from datetime import datetime, timedelta
import math,re
import traceback


from utils import Redisfactory

from flask import  g, jsonify, render_template, make_response, request, redirect,url_for, session, abort, current_app

from service.models import *
from service.trade import trade
from service.authority import *
from catgateio.GateIO import GateIO
from bson.objectid import ObjectId


logger = logging.getLogger('trade')
logger.setLevel(logging.DEBUG)
WHITELIST = ['/trade/']


@trade.route("/trade_index",methods=['POST','GET'])
@admin_permission.require(http_exception=401)
def trade_index():
    gt = GateIO("","")
    currency_pair = "eos_usdt"
    ticker = gt.ticker(currency_pair)
    datas = {
        "ticker":ticker,
    }
    return render_template('trade/trade_index.html',datas=datas,user_info = g.user_info)

@trade.route("/trade_list",methods=['POST','GET'])
@admin_permission.require(http_exception=401)
def trade_list():
    datas = {
    }
    return render_template('trade/trade_list.html',datas=datas,user_info = g.user_info)

@trade.route('/trade_info_list', methods=['GET','POST'])
@admin_permission.require(http_exception=401)
def trade_info_list():
    page = int(g.args.get("page",1))
    pnum = int(g.args.get("limit",20))
    trade_info_list = Trade_info.objects(user_info=g.user_info).all().skip((page-1)*pnum).limit(pnum)
    total = Trade_info.objects(user_info=g.user_info).count()
    data = []
    for trade in trade_info_list:
        data.append({
            "id":str(trade['id']),
            "strategy_name":trade['strategy_info']['name'],
            "in_cash":trade['in_cash'],
            "out_cash":trade['out_cash'],
            "rate":trade['rate'],
            "filledAmount":trade['filledAmount'],
            "trade_type":trade['trade_type'],
            "fee_total":trade['fee_total'],
            "status":trade['status'],
            "ctime":trade['ctime'].strftime("%Y-%m-%d %H:%M:%S"),
            "utime":trade['utime'].strftime("%Y-%m-%d %H:%M:%S"),
        })
    results = {
        "code":0,
        "msg":"",
        "count":total,
        "data":data
        }
    # g.results['datas'] = user_wallet_list
    return jsonify(results)



@trade.route("/trade_strategy_list",methods=['POST','GET'])
@admin_permission.require(http_exception=401)
def trade_strategy_list():
    pairs_list = Pairs.objects().all()
    gateio_info_list = Gateio_info.objects(user_info=g.user_info).all()
    datas = {
        "pairs_list":pairs_list,
        "gateio_info_list":gateio_info_list,
    }
    return render_template('trade/trade_strategy.html',datas=datas,user_info = g.user_info)


@trade.route('/strategy_info_list', methods=['GET','POST'])
@admin_permission.require(http_exception=401)
def strategy_info_list():
    page = int(g.args.get("page",1))
    pnum = int(g.args.get("limit",20))
    strategy_list = Strategy_info.objects(user_info=g.user_info,status__lte=20).all().skip((page-1)*pnum).limit(pnum)
    total = Strategy_info.objects(user_info=g.user_info,status__lte=20).count()
    data = []
    for strategy in strategy_list:
        data.append({
            "id":str(strategy['id']),
            "name":strategy['name'],
            "buy_point":strategy['buy_point'],
            "sell_point":strategy['sell_point'],
            "filledrate":strategy['filledrate'],
            "stop_point":strategy['stop_point'],
            "currency_pair":strategy['currency_pair'],
            "fee_total":strategy['fee_total'],
            "gateio":strategy['gateio_info']['name'],
            "is_loop":strategy['is_loop'],
            "status":strategy['status'],
            "ctime":strategy['ctime'].strftime("%Y-%m-%d %H:%M:%S"),
            "utime":strategy['utime'].strftime("%Y-%m-%d %H:%M:%S"),
        })
    results = {
        "code":0,
        "msg":"",
        "count":total,
        "data":data
        }
    # g.results['datas'] = user_wallet_list
    return jsonify(results)


@trade.route('/add_strategy', methods=['GET','POST'])
@admin_permission.require(http_exception=401)
def add_strategy():
    name = g.args.get("strategy_name","").strip()
    oid = g.args.get("oid","").strip()
    currency_pair = g.args.get("currency_pair","").strip()
    buy_point = float(g.args.get("buy_point","0").strip())
    sell_point = float(g.args.get("sell_point","0").strip())
    stop_point = float(g.args.get("stop_point","0").strip())
    filledrate = float(g.args.get("filledrate","0").strip())
    is_loop = int(g.args.get("is_loop","0").strip())
    fee_total = fee_total = (sell_point*(1-0.002)-buy_point*(1+0.002))
    objectid = ObjectId(oid)
    gateio_info = Gateio_info.objects(id=objectid).first()
    strategy = Strategy_info()
    strategy.name=name
    strategy.user_info=g.user_info
    strategy.gateio_info=gateio_info
    strategy.currency_pair=currency_pair
    strategy.buy_point=buy_point
    strategy.sell_point=sell_point
    strategy.stop_point=stop_point
    strategy.filledrate=filledrate
    strategy.fee_total=fee_total
    strategy.is_loop=is_loop
    strategy.save()
    return jsonify(g.results)

@trade.route('/del_strategy', methods=['GET','POST'])
@admin_permission.require(http_exception=401)
def del_strategy():
    oid = g.args.get("oid","").strip()
    objectid = ObjectId(oid)
    strategy = Strategy_info.objects(id=objectid).first()
    # strategy.delete()
    strategy.update(status=21)
    return jsonify(g.results)

@trade.route('/update_strategy', methods=['GET','POST'])
@admin_permission.require(http_exception=401)
def update_strategy():
    oid = g.args.get("oid","").strip()
    objectid = ObjectId(oid)
    strategy = Strategy_info.objects(id=objectid).first()
    if strategy['status']==1:
        strategy.update(status=11)
    elif strategy['status']==2:
        strategy.update(status=12)
    elif strategy['status']==0 or strategy['status']==11:
        strategy.update(status=1)
    elif strategy['status']==12:
        strategy.update(status=2)
    else:
        g.results['datas']['code']=2
        g.results['msg']='其他错误'
    return jsonify(g.results)

###############    interface   ########################

#----------------------------------------------------------------------------------------------------------------------------------------



